<?php

namespace api\guess\Services;

use api\index\controller\CommonController;
use app\admin\model\BatMatchModel;
use app\admin\model\ChangeCoinModel;
use app\admin\model\MemberModel;
use think\Db;
use app\admin\model\BatOrderModel;

class  RefundService
{
    //判断比赛结果
    public function match_result($id)
    {
        $bat = BatMatchModel::get($id);
        if (!$orders = $bat->betOrder()->where('status', BatOrderModel::STATUS_AWAIT)->select()) {
            return false;
        }
        foreach ($orders as $key => $vaule) {
            switch ($vaule->type) {
                case 0: //猜胜负结果
                    $result = $bat->victory_result();
                    break;
                case 1: //猜让球结果
                    $result = $bat->give_result();
                    break;
                case 2: //猜大小结果
                    $result = $bat->size_result();
                    break;
                default :
                    return false;
            }

            if ($vaule->type !== 1 && $result == 1) {
                //作废退款
                $this->refund($vaule, BatOrderModel::STATUS_CANCELLATION);
            } else {
                //判断是否中奖
                if ($result == $vaule->guess_type) {
                    //退款
                    $this->refund($vaule);
                } else {
                    //修改中奖状态为未中奖
                    $vaule->status = BatOrderModel::STATUS_NOT_WINNER;
                }
                $vaule->save();
            }
        }
    }

    //退款球币
    public function refund($order, $status = 0)
    {
        Db::transaction(function () use ($order, $status) {
            $member = MemberModel::get($order->member_id);
            if ($status == BatOrderModel::STATUS_CANCELLATION) { //作废
                $coin = $order->bet_coin;
                //修改中奖状态为作废
                $order->status = BatOrderModel::STATUS_CANCELLATION;
                $order->save();
            } else { //中奖
                //修改用户表球币
                $coin = $order->win_coin + $order->bet_coin;
                CommonController::changeCoin($order->member_id, ChangeCoinModel::BET_RETURN_PROFIT, $order->id, '投注返回盈利', '+' . $order->win_coin, $coin + $member->coin);
                //修改中奖状态为已中奖
                $order->status = BatOrderModel::STATUS_WINNER;
            }
            //球币变动插入数据
            CommonController::changeCoin($order->member_id, ChangeCoinModel::BET_RETURN_CAPITAL, $order->id, '投注返回本金', '+' . $order->bet_coin, $order->bet_coin + $member->coin);
            $member->coin += $coin;
            $member->save();
        });

    }

}